<script setup>
import { ref, onMounted, reactive, readonly } from 'vue'
import axios from 'axios'  // 导入 axios 库
import easyapi from '../../api'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useRouter } from 'vue-router';


const router = useRouter();
const navigateTo = (path) => {
  router.push(`/${path}`);
};


// 定义绑定数据
const allData = ref([]);
// 当前页显示的数据 
const tableData = ref([]);

// 分页查询
// 分页状态
const currentPage = ref(1);
const pageSize = ref(10); // 每页显示的数量
const total = ref(0); // 数据总数

//存储用户信息
const userInfo = ref({});
const username = ref('');
//分类页面地址数组
const classType = ref(["classa","classb","classc","classd","classe","classf","classg","classh","classi","classj","goodss"])

// 计算当前页数据
const paginate = () => {
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    tableData.value = allData.value.slice(start, end);
};
// 挂载页面时查询数据
onMounted(async function() {
    try {
        const result = await easyapi.get("/api/inventory/classd");
        allData.value = result.data;
        total.value = allData.value.length;
        paginate();
    } catch (error) {
        ElMessage({
            type: 'error',
            message: '数据加载失败: ' + (error.response?.data?.message || '未知错误'),
        });
    }
    const result = await easyapi.get('/api/currentusername');
    console.log(result);
    username.value = result.data.user_name;
    const userInfoResult = await easyapi.get(`/api/user/getusername?user_name=${username.value}`);
    userInfo.value = userInfoResult.data;
    console.log(userInfo.value);
    console.log(classType.value[0]);
    if(userInfo.value.role_id == 0){
        for(let i = 0; i < 11 ; i++){
            classType.value[i] = "goodsstaff/" + classType.value[i];
            console.log(classType.value[i])
        }
    }
});
// 处理分页变化
const handlePageChange = (newPage) => {
    currentPage.value = newPage;
    paginate();
};



// 查询条件
const query = ref(''); 
async function searchInventory(keyword, isdel = null, isshelf = null) {
    try {
        const response = await axios.get('/api/inventory/search', {
            params: { keyword, isdel, isshelf }
        });
        console.log('查询结果:', response.data);
        // 搜索结果赋值给 allData，并刷新表格
        allData.value = response.data.data;
        total.value = allData.value.length;
        paginate();
    } catch (error) {
        console.error('查询库存商品失败:', error);
        ElMessage({
            type: 'error',
            message: '查询失败: ' + (error.response?.data?.message || '未知错误'),
        });
    }
}
function searchProducts() {
    searchInventory(query.value);
}
// 重置按钮点击事件，刷新到只查看数据库中 isdel 和 isshelf 为 0 的数据
function resetSearchData() {
    query.value = ''; // 清空搜索条件
    searchInventory('', 0, 0); // 重新加载 isdel 和 isshelf 为 0 的商品
}



// 删除商品
const del = function(index, row) {
    ElMessageBox.confirm(
        "确定要删除该行数据吗?",
        "提示框",
        {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: 'warning',
        }
    ).then(function() {
        // 提交数据
        easyapi.del("/api/inventory/del", row.product_id);
        // 刷新表格数据
        tableData.value.splice(index, 1);
        // 提示删除成功
        ElMessage({
            type: 'success',
            message: '删除成功',
        });
    });
}

// 下架商品
const shelf = function(index, row) {
    ElMessageBox.confirm(
        "确定要下架该商品吗?",
        "提示框",
        {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: 'warning',
        }
    ).then(function() {
        // 提交数据
        easyapi.del("/api/inventory/shelf", row.product_id);
        // 刷新表格数据
        tableData.value.splice(index, 1);
        // 提示下架成功
        ElMessage({
            type: 'success',
            message: '下架成功',
        });
    });
}


//    编辑
// 控制编辑信息窗口是否显示
const editWinVisible = ref(false);
// 编辑数据绑定对象
const editObject = ref({});
// 保存编辑数据
const editSave = async function() {
    try {
        // 发送请求，URL中包含 product_id
        await easyapi.putJson(`/api/inventory/edit/${editObject.value.product_id}`, editObject.value);
        // 提示
        ElMessage({
            type: 'success',
            message: '保存成功',
        });
        // 保存前检查
        console.log("Edit Object: ", editObject.value);
        // 刷新表格
        // 重新获取数据，并只刷新当前页
        let result = await easyapi.get("/api/inventory/classd");
        allData.value = result.data;  // 更新 allData
        total.value = allData.value.length; // 更新 total
        paginate();  // 重新计算分页数据
        // 关闭编辑窗口
        editWinVisible.value = false;
    } catch (error) {
        // 错误处理
        ElMessage({
            type: 'error',
            message: '保存失败: ' + (error.response?.data?.message || '未知错误'),
        });
    }
}
// 点击编辑按钮执行的方法
const edit = function(index, row) {
    // 绑定要修改的数据
    editObject.value = { ...row };
    // 打开对话框
    editWinVisible.value = true;
}
// 关闭编辑窗口
const closeEditWin = () => {
    editWinVisible.value = false;
}


// 格式化日期函数
const formatDate = (date) =>{
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
}

// 计算属性来实时更新日期
const formattedDate = ref(formatDate(new Date()));

// 在组件挂载时，开始一个计时器来实时更新日期
onMounted(() => {
  setInterval(() => {
    formattedDate.value = formatDate(new Date());
  }, 1000);  // 每秒更新一次时间
});

//    新增
// 控制新增信息窗口是否显示
const addWinVisible = ref(false);
// 新增数据绑定对象
const addObject = ref({
  product_id: '',
  product_name: '',
  location: '',
  number: 0, // 初始化商品数量为0
  util: '',
  in_price: '',
  out_price: '',
  class_id: '',
  last_date: formatDate(new Date())  // 初始化为当前时间
});
//  表单验证
const addFormRef=ref(null);
const rules=reactive({
    product_id:[{required:true,message:'请输入商品编码',trigger:'blur'}],
    product_name:[{required:true,message:'请输入商品名称',trigger:'blur'}],
    location:[{required:true,message:'请输入商品位置',trigger:'blur'}],
    number:[{required:true,message:'请输入商品数量',trigger:'blur'}],
    util:[{required:true,message:'请输入商品单位',trigger:'blur'}],
    in_price:[{required:true,message:'请输入入库价格',trigger:'blur'}],
    out_price:[{required:true,message:'请输入出库价格',trigger:'blur'}],
    class_id:[{required:true,message:'请输入商品类型',trigger:'blur'}],
    last_date:[{required:true,message:'请输入日期',trigger:'blur'}],

})
// 保存新增
const addSave = async () => {
    addFormRef.value.validate(async (valid)=>{
        if(valid){
            try {
                // 发送请求，URL 中的 product_id 可以忽略，假设接口是 /api/inventory/add
                await easyapi.postJson('/api/inventory/add', addObject.value);
                // 提示保存成功
                ElMessage({
                    type: 'success',
                    message: '新增成功',
                });
                // 刷新表格数据
                let result = await easyapi.get('/api/inventory/all');
                allData.value = result.data;
                paginate(); // 更新分页
                // 关闭新增窗口
                addWinVisible.value = false;
            } catch (error) {
                // 错误处理
                ElMessage({
                    type: 'error',
                    message: '新增失败: ' + (error.response?.data?.message || '未知错误'),
                });
            }
        }else{
            ElMessage.error('请检查表单填写是否正确');
        }
    })
    
};


// 显示窗口
const openAddWin = () => {
    // addObject.value = {};
    addWinVisible.value = true;
}

const closeAddWin = () => {
    addWinVisible.value = false;
}




</script>

<template>
    <!--输入及刷新
     <el-input 
    v-model="query" 
    placeholder="输入商品名称或商品ID进行查询"
    @input="searchProducts" 
    style="flex: 1; max-width: 300px; height: 40px;" 
    size="medium"
    clearable/> 
    -->
    <!-- 点击按钮刷新 -->
    <el-input 
        v-model="query" 
        placeholder="输入商品名称或商品ID进行查询" 
        @change="searchProducts" 
        style="flex: 1; max-width: 300px; height: 40px;" 
        size="medium"
        clearable/>

        <el-button type="primary" @click="searchProducts" size="medium">查询</el-button>
        <el-button type="warning" @click="resetSearchData" size="medium">重置</el-button>
        <el-button type="success" size="medium" @click="openAddWin">新增商品</el-button>

  <!-- 点击按钮跳转 -->
  <div style="margin-top: 10px; background-color: #ffffff; padding: 10px;">
    <el-button type="primary" plain @click="navigateTo(classType[10])">全部商品</el-button>
    <el-button type="primary" plain @click="navigateTo(classType[0])">电子产品</el-button>
    <el-button type="primary" plain @click="navigateTo(classType[1])">家居用品</el-button>
    <el-button type="primary" plain @click="navigateTo(classType[2])">食品饮料</el-button>
    <el-button type="primary" plain @click="navigateTo(classType[3])">办公用品</el-button>
    <el-button type="primary" plain @click="navigateTo(classType[4])">美容护肤</el-button>
    <el-button type="primary" plain @click="navigateTo(classType[5])">运动器材</el-button>
    <el-button type="primary" plain @click="navigateTo(classType[6])">汽车配件</el-button>
    <el-button type="primary" plain @click="navigateTo(classType[7])">书籍杂志</el-button>
    <el-button type="primary" plain @click="navigateTo(classType[8])">厨房用品</el-button>
    <el-button type="primary" plain @click="navigateTo(classType[9])">其他商品</el-button>
  </div>

        <!-- start 显示所有商品信息的表格 -->
        <el-table :data="tableData" style="width: 100%">
            <el-table-column label="序号" width="80">
        <template v-slot="scope">
            {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
        </template>
        </el-table-column>
        <el-table-column prop="product_id" label="商品编码" width="100" />
        <el-table-column prop="product_name" label="商品名称" width="100" />
        <el-table-column prop="location" label="库存位置" width="80" />
        <el-table-column prop="number" label="库存数量" width="80" />
        <el-table-column prop="util" label="单位" width="80" />
        <el-table-column prop="in_price" label="进货价" width="80" />
        <el-table-column prop="out_price" label="出货价" width="80" />
        <el-table-column prop="class_name" label="商品类别" width="100" />
        <el-table-column prop="last_date" label="最后调整时间" min-width="80"/>
        <el-table-column label="操作">
            <template #default="scope">
                <el-button type="warning" @click="edit(scope.$index, scope.row)">编辑</el-button>
                <el-button type="info" @click="shelf(scope.$index, scope.row)">下架</el-button>
                <el-button type="danger" @click="del(scope.$index, scope.row)">删除</el-button>
            </template>
        </el-table-column>
        </el-table>
    <!-- end 显示商品信息的表格 -->

    <!-- start 分页组件 -->
    <el-pagination
        background
        layout="prev, pager, next"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        @current-change="handlePageChange">
    </el-pagination>
    <!-- end 分页组件 -->


    <!-- start 编辑信息的弹出框 -->
    <el-dialog v-model="editWinVisible" title="编辑" width="500">
    <el-form :model="editObject">
        <el-form-item label="商品名称" label-width="80">
            <el-input v-model="editObject.product_name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="商品位置" label-width="80">
            <el-input v-model="editObject.location" autocomplete="off" />
        </el-form-item>
        <!-- <el-form-item label="商品数量" label-width="80">
            <el-input v-model="editObject.number" autocomplete="off" />
        </el-form-item> -->
        <el-form-item label="单位" label-width="80">
            <el-input v-model="editObject.util" autocomplete="off" />
        </el-form-item>
        <el-form-item label="入库价格" label-width="80">
            <el-input v-model="editObject.in_price" autocomplete="off" />
        </el-form-item>
        <el-form-item label="出库价格" label-width="80">
            <el-input v-model="editObject.out_price" autocomplete="off" />
        </el-form-item>
        <el-form-item label="商品类型" label-width="80">
            <el-select v-model="editObject.class_id" placeholder="请选择商品类型">
                <el-option label="电子产品" :value="1" />
                <el-option label="家居用品" :value="2" />
                <el-option label="食品饮料" :value="3" />
                <el-option label="办公用品" :value="4" />
                <el-option label="美容护肤" :value="5" />
                <el-option label="运动器材" :value="6" />
                <el-option label="汽车配件" :value="7" />
                <el-option label="书籍杂志" :value="8" />
                <el-option label="厨房用品" :value="9" />
                <el-option label="其他" :value="0" />
            </el-select>
        </el-form-item>
    </el-form>

    <template #footer>
        <div class="dialog-footer">
            <el-button @click="closeEditWin">取消</el-button>
            <el-button type="primary" @click="editSave">保存</el-button>
        </div>
    </template>
</el-dialog>

    <!-- end 编辑信息的弹出框 -->

    <!-- start 新增商品信息的弹出框 -->
    <el-dialog v-model="addWinVisible" title="新增商品信息" width="500">
        <el-form :model="addObject" :rules="rules" ref="addFormRef">
            <el-form-item label="商品编码" label-width="80"  prop="product_id">
                <el-input v-model="addObject.product_id" autocomplete="off" />
            </el-form-item>
            <el-form-item label="商品名称" label-width="80" prop="product_name">
                <el-input v-model="addObject.product_name" autocomplete="off" />
            </el-form-item>
            <el-form-item label="商品位置" label-width="80" prop="location">
                <el-input v-model="addObject.location" autocomplete="off" />
            </el-form-item>
            <el-form-item label="商品数量" label-width="80" prop="number">
                <el-input v-model="addObject.number" :readonly="true" autocomplete="off" />
                 <!-- <el-text>0</el-text> -->
            </el-form-item>
            <el-form-item label="商品单位" label-width="80" prop="util">
                <el-input v-model="addObject.util" autocomplete="off" />
            </el-form-item>
            <el-form-item label="入库价格" label-width="80" prop="in_price">
                <el-input v-model="addObject.in_price" autocomplete="off" />
            </el-form-item>
            <el-form-item label="出库价格" label-width="80" prop="out_price">
                <el-input v-model="addObject.out_price" autocomplete="off" />
            </el-form-item>
            <el-form-item label="商品类型" label-width="80" prop="class_id">
                <el-select v-model="addObject.class_id" placeholder="请选择商品类型">
                    <el-option label="电子产品" :value="1" />
                    <el-option label="家居用品" :value="2" />
                    <el-option label="食品饮料" :value="3" />
                    <el-option label="办公用品" :value="4" />
                    <el-option label="美容护肤" :value="5" />
                    <el-option label="运动器材" :value="6" />
                    <el-option label="汽车配件" :value="7" />
                    <el-option label="书籍杂志" :value="8" />
                    <el-option label="厨房用品" :value="9" />
                    <el-option label="其他" :value="0" />
                </el-select>
            </el-form-item>
            <el-form-item label="日期:" label-width="80" prop="last_date" >
                <el-input 
                v-model="addObject.last_date" :readonly="true" autocomplete="off"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="closeAddWin">取消</el-button>
                <el-button type="primary" @click="addSave">保存</el-button>
            </div>
        </template>
    </el-dialog>
    <!-- end 新增商品信息的弹出框 -->
</template>

<style scoped>
.main-container {
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
</style>